package com.glory.brepda.activity.mfg;


import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.ItmeDataSortAdapter;
import com.glory.brepda.adapter.XXItmeDataSortAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.entity.EdcEntity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class EdcLotActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etEdcName)
    FreeUI_ClearEditText etEdcName;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpID)
    FreeUI_ClearEditText etEqpID;
    @BindView(R.id.tvEDCsetdescription)
    TextView tvEDCsetdescription;
    @BindView(R.id.tvUpImage)
    TextView tvUpImage;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.rvBINInfoList)
    RecyclerView rvBINInfoList;
    @BindView(R.id.rbQualified)
    RadioButton rbQualified;
    @BindView(R.id.rbUnQualified)
    RadioButton rbUnQualified;
    private EdcEntity body;
    private XXItmeDataSortAdapter mItmeDataSortAdapter;
    private ArrayList<String> sList = new ArrayList<>();
    private ArrayList<String> objectList = new ArrayList<>();
    private ArrayList<String> isList = new ArrayList<>();
    private String STEPNAME = "";
    private LotInfoEntity mLotInfoEntity;
    static final int REQUEST_IMAGE_CAPTURE = 1;
    private String imageData = "";
    private String mFilePath = "";
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_xxitmedatasort;
    }

    @Override
    protected void initView() {
        tvTitle.setText("数据收集记录批次");
        setMainLayout(llMain);

        mItmeDataSortAdapter = new XXItmeDataSortAdapter(null);
        mItmeDataSortAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mItmeDataSortAdapter.isFirstOnly(true);
        initRecyclerView(rvBINInfoList, this);
        rvBINInfoList.setAdapter(mItmeDataSortAdapter);

        // android 7.0系统解决拍照的问题
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

    }

    @Override
    protected void initData() {
        initEdit(etEdcName, this::requestEdcData);
        initEdit(etLot, s -> LotUtils.searchLotInfo(EdcLotActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
            @Override
            public void onSuccess(LotInfoEntity response) {
                mLotInfoEntity = response;
                STEPNAME = response.getLOT().getSTEPNAME();
            }

            @Override
            public void onFail(Throwable t) {
                loadError(t,"LOTQUERY");
            }
        }));
    }

    @OnClick({R.id.tvBaseSubmit,R.id.tvUpImage})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                if (getText(etLot).equals("")){
                    showToast("请扫描批次号",false);
                    return;
                }
                if (getText(etEdcName).equals("")){
                    showToast("请输入项集名称",false);
                    return;
                }
                if (mLotInfoEntity == null){
                    showToast("暂无批次信息",false);
                    return;
                }

                submit();
                break;
            case R.id.tvUpImage:
                getImage();
                break;
        }
    }

    private void getImage() {
        mFilePath = Environment.getExternalStorageDirectory().getPath()+"/" + "mytest.png";
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri mUri = Uri.fromFile(new File(mFilePath));
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        startActivityForResult(openCameraIntent, 1);
    }

    private void submit() {

        showSubmitDialog(new onSubmitListener() {
            @Override
            public void setOnSubmitListener() {

                FreeUI_EntityCallBack<BaseResponseBean<EdcEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EdcEntity>>
                        (new TypeToken<BaseResponseBean<EdcEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<EdcEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                            showConfirmDialog(EdcLotActivity.this,"提交成功");
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<EdcEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(),"BRESAVEEDCDATA");
                    }
                };

                JsonObject map = new JsonObject();
                map.addProperty("ACTIONTYPE","SAVE");
                map.addProperty("LOTID",getText(etLot));
                map.addProperty("MEQPID",getText(etEqpID));
                map.addProperty("PEQPID",getText(etEqpID));
                map.addProperty("OPERATOR1",Constant.CURRENT_USER);
                map.addProperty("LOTRRN",mLotInfoEntity.getLOT().getOBJECTRRN());
                map.addProperty("STEPNAME",STEPNAME);
                SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                Date date = new Date(System.currentTimeMillis());
                map.addProperty("EDCTIME",formatter.format(date));
                map.addProperty("EDCNAME",getText(etEdcName));
                map.addProperty("PICTUREPATH",imageData);
                map.addProperty("JUDGE1",rbQualified.isChecked()?"OK":"NG");
                ArrayList<EdcEntity.EdcItemSetLine> edcItemSetLineList = new ArrayList<>();
                for (int i=0;i<sList.size();i++) {
                    EdcEntity.EdcItemSetLine edcItemSetLine = new EdcEntity.EdcItemSetLine();
                    edcItemSetLine.setOBJECTRRN(Long.parseLong(objectList.get(i)));
                    edcItemSetLine.setISMANDATORY(isList.get(i));
                    ArrayList<EdcEntity.EdcItemSetLine.EDCItemData> edcItemData1 = new ArrayList<>();
                    for (EdcEntity.EdcSet data:mItmeDataSortAdapter.getData()){
                        if (sList.get(i).equals(data.getEDCSETNAME())){
                            EdcEntity.EdcItemSetLine.EDCItemData edcItemData = new EdcEntity.EdcItemSetLine.EDCItemData();
                            edcItemData.setDCDATA(data.getVALUE());
                            edcItemData.setDCNAME(data.getITEM());
                            edcItemData.setDCREMARK(data.getCOMMENT());
                            edcItemData.setISMANDATORY(data.getISMANDATORY());
                            edcItemData1.add(edcItemData);
                        }
                    }
                    edcItemSetLine.setEDCITEMDATALIST(edcItemData1);
                    edcItemSetLineList.add(edcItemSetLine);
                }

                map.add("EDCITEMSETLINELIST",new JsonParser().parse(new Gson().toJson(edcItemSetLineList)).getAsJsonArray());
                NetUtils.requestPostNet("IF.BRESAVEEDCDATA","BRESAVEEDCDATA", EdcLotActivity.this,map,callBack);
            }
        });
    }

    private void requestEdcData(String name) {
        FreeUI_EntityCallBack<BaseResponseBean<EdcEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EdcEntity>>
                (new TypeToken<BaseResponseBean<EdcEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EdcEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    body = response.body().getResponse().getBody();
                    List<EdcEntity.EdcSet> edcsetlist = response.body().getResponse().getBody().getEDCSETLIST();
                    ArrayList<EdcEntity.EdcSet> edcSets = new ArrayList<>();
                    for (int i = 0; i < edcsetlist.get(0).getEDCSETITEMLINELIST().size(); i++) {
                        EdcEntity.EdcSet edcSet = new EdcEntity.EdcSet();
                        edcSet.setITEM(edcsetlist.get(0).getEDCSETITEMLINELIST().get(i).getITEMDESC());
                        edcSet.setEDCSETNAME(edcsetlist.get(0).getEDCSETITEMLINELIST().get(i).getNAME());
                        edcSet.setEDCSETDESCRIPTION(edcsetlist.get(0).getEDCSETDESCRIPTION());
                        edcSet.setDESCRIPTION(edcsetlist.get(0).getEDCSETITEMLINELIST().get(i).getDESCRIPTION());
                        edcSet.setISMANDATORY(edcsetlist.get(0).getEDCSETITEMLINELIST().get(i).getISMANDATORY());
                        edcSets.add(edcSet);
                        if (!sList.contains(edcsetlist.get(0).getEDCSETITEMLINELIST().get(i).getNAME())){
                            sList.add(edcsetlist.get(0).getEDCSETITEMLINELIST().get(i).getNAME());
                            objectList.add(edcsetlist.get(0).getEDCSETITEMLINELIST().get(i).getOBJECTRRN());
                            isList.add(edcsetlist.get(0).getEDCSETITEMLINELIST().get(i).getISMANDATORY());
                        }
                    }
                    mItmeDataSortAdapter.setNewData(edcSets);

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EdcEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"EDCCURRENT");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","QUERYBYEDCNAME");
        map.addProperty("EDCSETNAME",name);
        NetUtils.requestPostNet("IF.EDCITEMSET","Common", EdcLotActivity.this,map,callBack);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
//            assert data != null;
//            Bundle extras = data.getExtras();
//            Bitmap imageBitmap = (Bitmap) extras.get("data");
//            imageData = bitmapToBase64(imageBitmap);

            Uri uri1 = Uri.fromFile(new File(mFilePath));
            ContentResolver cr = this.getContentResolver();
            try {
                InputStream is = cr.openInputStream(uri1);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize =3;
                Bitmap bitmap = BitmapFactory.decodeStream(is,null,options);
                imageData = bitmapToBase64(bitmap);
            }
            catch(Exception e)
            {
                Log.i("lyf", e.toString());
            }


            if (!imageData.equals("")){
                tvUpImage.setText("更换图片");
            }else {
                tvUpImage.setText("点击上传图片");
                showToast("图片加载失败",false);
            }

        }

    }

    private static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}